#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>

int cnt = 0;
std::string message;
void *writework(void *ptr)
{
    pthread_rwlock_t *rwlock = (pthread_rwlock_t *)ptr;
    while (true)
    {
        pthread_rwlock_wrlock(rwlock);
        cnt++;
        message = "This is " + std::to_string(cnt) + "piece message";
        pthread_rwlock_unlock(rwlock);
        sleep(1);
    }
}

void *readwork(void *ptr)
{
    pthread_rwlock_t *rwlock = (pthread_rwlock_t *)ptr;
    while (true)
    {
        pthread_rwlock_rdlock(rwlock);
        std::cout<< "Thread id: " << gettid() << "Get message: " << message << std::endl;
        pthread_rwlock_unlock(rwlock);
        usleep(500000);
    }
}

int main()
{

    pthread_t w1;
    pthread_t r1;
    pthread_t r2;

    pthread_rwlock_t *rwlock = new pthread_rwlock_t;
    pthread_rwlock_init(rwlock, nullptr);

    pthread_create(&w1, nullptr, writework, rwlock);
    pthread_create(&r1, nullptr, readwork, rwlock);
    pthread_create(&r2, nullptr, readwork, rwlock);

    pthread_join(w1, nullptr);
    pthread_join(r1, nullptr);
    pthread_join(r2, nullptr);

    return 0;
}